const db = require('../db/index')

exports.all = (req, res) => { // 获取info表全部数据
  const sql = 'select * from info'
  db.query(sql, (err, data) => {
    if (err) {
      return res.send('错误：' + err.message)
    }
    res.send(data)
  })
}
exports.get = (req, res) => { // 通过id查询数据
  const sql = 'select * from info where id = ?' // ？用于占位
  db.query(sql, [req.query.id], (err, data) => {
    if (err) {
      return res.send('错误：' + err.message)
    }
    res.send(data)
  })
}

exports.del = (req, res) => { // 通过id删除数据
  const sql = 'delete from info where id = ?'
  db.query(sql, [req.query.id], (err, data) => {
    if (err) {
      return res.send('错误：' + err.message)
    }
    if (data.affectedRows > 0) {
      res.send({
        status: 200,
        message: '删除成功'
      })
    } else {
      res.send({
        status: 202,
        message: '删除失败'
      })
    }
  })
}

exports.add = (req, res) => { // 向info表添加数据
  const sql = 'insert into info (id,time,txt) values (?,?,?,?)'
  db.query(sql, [req.query.id, req.query.time, req.query.txt], (err, data) => {
    if (err) {
      return res.send('错误：' + err.message)
    }
    if (data.affectedRows > 0) {
      res.send({
        status: 200,
        message: 'success'
      })
    } else {
      res.send({
        status: 202,
        message: 'error'
      })
    }
  })
}

exports.update = (req, res) => { // 通过id更新数据
  const sql = 'update info set time = ?, txt = ? where id = ?'
  db.query(sql, [req.query.time, req.query.txt, req.query.id], (err, data) => {
    if (err) {
      return res.send('错误：' + err.message)
    }
    if (data.changedRows > 0) {
      res.send({
        status: 200,
        message: 'success'
      })
    } else {
      res.send({
        status: 202,
        message: 'error'
      })
    }
  })
}
